import { Inject, Injectable } from '@nestjs/common';
import { ImclientConfig } from './type/config';
import { createHash } from 'crypto';
import { HttpService } from '@nestjs/axios';

@Injectable()
export class ImclientService {
    private baseUrl = 'https://open.yunxinapi.com/im/v2/'
    private baseUrl2 = 'https://open.yunxinapi.com/im/v2.1/'
    constructor(
        @Inject('IM_CONFIG') private config: ImclientConfig,
        private readonly httpService:HttpService,
    ) {
        
    }


    private headers() {
        const headers:any = {
            AppKey: this.config.appKey,
            Nonce: this.randString(20),
            CurTime: String(Math.floor(Date.now() / 1000)),
            'Content-Type' : 'application/json'
        }
        
        headers.CheckSum = createHash('sha1').update(this.config.appSecret + headers.Nonce + headers.CurTime).digest('hex');

       
        return headers
    }

    async createUser(accountId:string, user_information?:{[key:string]:any}) {
        try {

            const params:any = {
                account_id: accountId
            }
            if(user_information) {
                params.user_information = user_information
            }


            const res = await this.httpService.axiosRef.post('accounts', params, {
                baseURL: this.baseUrl,
                headers: {
                    ...this.headers()
                },
            })

            if(res.data != null) {
                return res.data
            }

        } catch (error) {
            
        }


        return null
    }

    async update(accountId:string, info?:{[key:string]:any}) {
        try {

            const res = await this.httpService.axiosRef.patch('users/' + accountId, info, {
                baseURL: this.baseUrl,
                headers: {
                    ...this.headers()
                },
            })

            if(res.data != null) {
                return res.data
            }

        } catch (error) {
            
        }


        return null
    }

    async disable(accountId:string, params?:{[key:string]:any}) {
        try {
            const res = await this.httpService.axiosRef.patch(`accounts/${accountId}/actions/disable`, params, {
                baseURL: this.baseUrl,
                headers: {
                    ...this.headers()
                },
            })

            if(res.data != null) {
                return res.data
            }

        } catch (error) {
            
        }


        return null
    }

    async refreshToken(accountId) {
        try {
            const res = await this.httpService.axiosRef.patch(`accounts/${accountId}/actions/refresh_token`, null, {
                baseURL: this.baseUrl,
                headers: {
                    ...this.headers()
                },
            })

            if(res.data != null && res.data.code == 200) {
                return res.data
            }

        } catch (error) {
            
        }


        return null
    }

    async users(accountId:string[]) {
        try {
            const res = await this.httpService.axiosRef.get('users', {
                baseURL: this.baseUrl,
                headers: {
                    ...this.headers()
                },
                params: {
                    account_ids: accountId.join(',')
                }
            })


            if(res.data != null && res.data.code == 200) {
                return res.data.data.success_list
            }

        } catch (error) {
            
        }


        return null
    }

    async onlineStatus(accountIds:string[]) {
        try {
            const res = await this.httpService.axiosRef.post('users/actions/online_status', {account_ids: accountIds}, {
                baseURL: this.baseUrl,
                headers: {
                    ...this.headers()
                },
            })

            if(res.data != null && res.data.code == 200) {
                return res.data.data.success_list
            }

        } catch (error) {
            
        }


        return null
    }

    async joinedTeams(accountId:string, params:any) {
        try {
            const res = await this.httpService.axiosRef.get(`team_members/${accountId}/actions/joined_teams`, {
                baseURL: this.baseUrl,
                headers: {
                    ...this.headers()
                },
                params: params
            })

            if(res.data != null && res.data.code == 200) {
                return res.data.data
            }

        } catch (error) {
            
        }


        return null
    }

    async teamMembers(teamId:string, params:any) {
        try {
            const res = await this.httpService.axiosRef.get(`teams/${teamId}/actions/list_members`, {
                baseURL: this.baseUrl2,
                headers: {
                    ...this.headers()
                },
                params: params
            })

            if(res.data != null && res.data.code == 200) {
                return res.data.data
            }

        } catch (error) {
            
        }


        return null
    }

    async getMarkReadInfo(params:any) {
        

        try {
            const res = await this.httpService.axiosRef.post('https://api.yunxinapi.com/nimserver/team/getMarkReadInfo.action', params, {
                headers: {
                    ...this.headers(),
                    'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
                }
            })


            if(res.data != null && res.data.code == 200) {
                return res.data.data
            }else {
                console.log(res.data)
            }

        } catch (error) {
            
        }


        return null
    }

    async friends(params:any) {
        try {
            const res = await this.httpService.axiosRef.get('friends', {
                baseURL: this.baseUrl,
                headers: {
                    ...this.headers()
                },
                params: params
            })

            if(res.data != null && res.data.code == 200) {
                return res.data.data
            }

        } catch (error) {
            
        }


        return null
    }

    async addFriends(accountId:string,friend_account_id:string) {
        try {
            const res = await this.httpService.axiosRef.post('friends?type=1', {account_id: accountId, friend_account_id:friend_account_id,type:1,extension:"official"}, {
                baseURL: this.baseUrl,
                headers: {
                    ...this.headers()
                },
            })


            if(res.data != null) {
                return res.data
            }

        } catch (error) {
            
        }


        return null
    }

    async batchSendMessage(params) {
        try {
            const res = await this.httpService.axiosRef.post('conversations/messages', params, {
                baseURL: this.baseUrl,
                headers: {
                    ...this.headers()
                },
            })


            if(res.data != null) {
                return res.data
            }

        } catch (error) {
            
        }


        return null
    }

    async delAllFriends(account_id:string) {
        try {
            const res = await this.httpService.axiosRef.get('friends', {
                baseURL: this.baseUrl,
                params: {account_id: account_id, limit: 100}
            })


            if(res.data != null) {
                if(res.data.items) {
                    res.data.items.forEach(row => {
                        this.httpService.axiosRef.delete('friends/' + account_id, {
                            baseURL: this.baseUrl,
                            data: {
                                friend_account_id: row.friend_account_id,
                                delete_alias: true,
                            }
                        })
                    })
                }
            }

        } catch (error) {
            
        }
    }

    async searchMessages(conversation_id, params:any) {

        // try {
        //     const res = await this.httpService.axiosRef.get(`messages/actions/team_read_receipt`, {
        //         baseURL: this.baseUrl,
        //         params: {
        //             team_id:"44826596272",
        //             team_type:1,
        //             sender_id:"2989239",
        //             message_server_id:3008261952800555011
        //         },
        //         headers: {
        //             ...this.headers()
        //         },

        //     })

        //     console.log(res)

        
        //     if(res.data != null) {
        //         return res.data
        //     }

        // } catch (error) {
            
        // }


        // return

        try {
            const res = await this.httpService.axiosRef.get(`conversations/${conversation_id}/messages`, {
                baseURL: this.baseUrl2,
                params: params,
                headers: {
                    ...this.headers()
                }

            })

            
        
            if(res.data != null) {
                return res.data
            }

        } catch (error) {
            
        }


        return null

    }

    async modifyMsg(params:any) {
        try {
            const res = await this.httpService.axiosRef.post('messages/actions/modifyMsg', params, {
                baseURL: this.baseUrl,
                headers: {
                    ...this.headers()
                },
            })


            if(res.data != null) {
                return res.data
            }

        } catch (error) {
            
        }


        return null
    }

    

    private randString(x) {
        let s = '';
        while (s.length < x && x > 0) {
            const v = Math.random() < 0.5 ? 32 : 0;
            s += String.fromCharCode(
                Math.round(Math.random() * (122 - v - (97 - v)) + (97 - v))
            )
        }

        return s;
    }


}
